//
// Created by wujehy on 2020/8/4.
//

#include "DaoManager.h"
#include "Dao/UserDB.h"
#include "Dao/IoTDB.h"

ManagerBase::Type DaoManager::type()
{
    return ManagerType_Dao;
}

void DaoManager::registerDB()
{
    if (user_database == nullptr)
    {
        user_database = new SQLite::Database( "user.db", SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE, 2000 );
    }
    UserDB *userDb = new UserDB;
//    userDb->context = netWorkWarpper;
    userDb->dbHander = user_database;

    auto pt1 = m_dao_map.insert( {userDb->type(), userDb} );
    if (!pt1.second)
    {
        delete userDb;
    }

    if (iot_database == nullptr)
    {
        iot_database = new SQLite::Database( "iot.db", SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE, 2000 );
    }
    IoTDB *ioTdb = new IoTDB;
//    ioTdb->context = netWorkWarpper;
    ioTdb->dbHander = iot_database;

    auto pt2 = m_dao_map.insert( {ioTdb->type(), ioTdb} );
    if (!pt2.second)
    {
        delete ioTdb;
    }
}

void DaoManager::init()
{
    registerDB();

    for (auto db : m_dao_map)
    {
        db.second->init();
    }
}

//void DaoManager::setNetWorkWarpper(NetWorkWarpper *netWorkWarpper)
//{
//    DaoManager::netWorkWarpper = netWorkWarpper;
//}

DaoManager::~DaoManager()
{

    for (auto d : m_dao_map)
    {
        if (d.second != nullptr)
        {
            delete d.second;
        }
    }

    if (user_database != nullptr)
    {
        delete user_database;
    }
    if (iot_database != nullptr)
    {
        delete iot_database;
    }
}

void DaoManager::init_finished()
{
    for (auto d : m_dao_map)
    {
        d.second->init_finished();
    }
}
